package com.smartpower.wattmeter.ui;

import android.Manifest;
import android.bluetooth.BluetoothGatt;
import android.content.res.AssetFileDescriptor;
import android.graphics.drawable.AnimationDrawable;
import android.view.View;
import android.view.animation.LinearInterpolator;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.android.basiclib.base.BaseFragment;
import com.android.basiclib.uitls.CommUtils;
import com.android.basiclib.uitls.Log.LogUtil;
import com.android.basiclib.uitls.NetWorkUtil;
import com.android.basiclib.uitls.SizeUtils;
import com.android.basiclib.uitls.ToastUtils;
import com.android.basiclib.view.FangIOSDialog;
import com.android.basiclib.view.LoadingDialogManager;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.clj.fastble.BleManager;
import com.clj.fastble.data.BleDevice;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.animation.ValueAnimator;
import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;
import com.smartpower.wattmeter.Constants;
import com.smartpower.wattmeter.R;
import com.smartpower.wattmeter.adapter.FastBleAdapter;
import com.smartpower.wattmeter.manager.FastBleManager;
import com.smartpower.wattmeter.manager.IFastBleManager;
import com.smartpower.wattmeter.manager.MyFastBleCallback;

import com.smartpower.wattmeter.utils.MediaUtil;
import com.yanzhenjie.permission.AndPermission;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class HomeScanFragment extends BaseFragment implements View.OnClickListener {

    private android.widget.FrameLayout mFlRootCircle;
    private View mLoadingCircleView;
    private android.widget.FrameLayout mFlClickCircle;
    private android.widget.ImageView mIvBleCenter;
    private boolean isCenterGifRuning;
    private AnimationDrawable mAnimationDrawable;
    private ObjectAnimator mAnimator;
    private View mFlLoadingCircle;
    private android.widget.LinearLayout mLlTopRightBox;
    private android.widget.TextView mTvTotalDevice;
    private android.widget.TextView mTvRescan;
    private android.widget.FrameLayout mFlListBox;
    private androidx.recyclerview.widget.RecyclerView mRvDevice;
    private List<BleDevice> mDatas = new ArrayList<>();
    private FastBleAdapter mDeviceAdapter;
    private android.widget.TextView mTvScanTips;
    private boolean isShowTop = false;

    private IFastBleManager<BleDevice> mBLEManager;
    private boolean isEdit = false;
    private BleDevice mBleDevice;

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_home_scan;
    }

    @Override
    protected void init() {
        initStatus();
        initBLE();
        initListener();
    }

    //蓝牙初始化-使用自定义的Manager-可以去Manager中设置初始化参数
    private void initBLE() {
        mBLEManager = FastBleManager.getInstance();
        mBLEManager.BLEInit(mActivity.getApplication(), new MyFastBleCallback<BleDevice>() {
            @Override
            public void BLEScanDevices(BleDevice devices) {
                if (devices != null)
                    addData2Show(devices);
            }

            @Override
            public void BLEScanFinish() {
                //扫描完成关闭动画
                stopGifAnim();
                mTvScanTips.setText("点击按钮，开始检测");
            }

            @Override
            public void BLEReadConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt) {
                mBleDevice = bleDevice;
                playSound("connect_success.wav");

                isEdit = false;
                mBLEManager.BLEReadNotifyData(bleDevice, gatt);

                //测试操作页面
//                BLEServicesListActivity.startInstance(bleDevice);
            }

            @Override
            public void BLEConnectFailed() {
            }

            @Override
            public void BLENotifyDataSuccessCallback(String data, BleDevice bleDevice) {
                //格式化之后的Json数据
                LoadingDialogManager.get().dismissLoading();
                LogUtil.e("读取数据回调成功了");

                if (isEdit) {
                    playSound("wirte_success.wav");
                    ToastUtils.makeText(mActivity, "写入 成功");
                    LiveEventBus.get().with(Constants.EVENT_BLE_WRITE_CALLBACK).post(true);
                } else {
                    playSound("read_sucess.wav");
                    DeviceDetailActivity.startInstance(data);
                }
            }
        });
    }

    /**
     * 播放语言文件
     */
    private void playSound(String name) {
        AssetFileDescriptor fd = null;
        try {
            fd = mActivity.getAssets().openFd(name);
            MediaUtil.getInstance().play(fd);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //扫描的数据添加到Adapter展示
    private void addData2Show(BleDevice devices) {

        mDeviceAdapter.addData(devices);

        mTvTotalDevice.setText("共检测到 " + mDeviceAdapter.getData().size() + " 个设备");

        if (!isShowTop && mDeviceAdapter.getData().size() > 0) {
            gotoTopShowList();
            isShowTop = true;
        }
    }


    //初始状态
    private void initStatus() {
        //测量完成之后，顶部的右侧布局先出去
        SizeUtils.forceGetViewSize(mLlTopRightBox, view -> {
            int width = mLlTopRightBox.getWidth();
            float needMoveWith = width + CommUtils.dip2px(20);
            ViewHelper.setTranslationX(mLlTopRightBox, needMoveWith);
        });

        //测量完成，底部列表先下去
        SizeUtils.forceGetViewSize(mFlListBox, view -> {
            int height = mFlListBox.getHeight();
            ViewHelper.setTranslationY(mFlListBox, height);
        });

        //初始化RV
        mRvDevice.setLayoutManager(new LinearLayoutManager(mContext));

        mDeviceAdapter = new FastBleAdapter(mDatas);
        mDeviceAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_RIGHT);
        mRvDevice.setAdapter(mDeviceAdapter);

    }


    @Override
    public void onResume() {
        super.onResume();
        checkBluetoothPermission();
    }

    /**
     * 检查蓝牙权限
     */
    private void checkBluetoothPermission() {
        AndPermission.with(this).runtime()
                .permission(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                .onGranted(data -> {
                    enableBluetooth();
                })
                .onDenied(data -> {
                    ToastUtils.makeText(mActivity, "需要同意定位权限才能使用蓝牙功能");
                })
                .start();
    }

    //检查是否开启蓝牙
    private void enableBluetooth() {

        if (!BleManager.getInstance().isBlueEnable()) {
            BleManager.getInstance().enableBluetooth();

        } else {

            boolean isSupport = BleManager.getInstance().isSupportBle();
            boolean isOpenBle = BleManager.getInstance().isBlueEnable();

            FangIOSDialog dialog = new FangIOSDialog(mActivity);

            if (!isSupport) {
                dialog.setTitle("提示")
                        .setMessage("你的设置不支持BLE蓝牙功能")
                        .setPositiveButton("OK", v -> {
                            dialog.dismiss();
                        })
                        .show();
            }
            if (!isOpenBle) {
                dialog.setTitle("提示")
                        .setMessage("你的没有开启蓝牙")
                        .setPositiveButton("OK", v -> {
                            dialog.dismiss();
                        })
                        .show();
            }

        }
    }


    //监听
    private void initListener() {

        mFlClickCircle.setOnClickListener(this);
        mTvRescan.setOnClickListener(this);

        //item的点击事件,连接指定的蓝牙设备
        mDeviceAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            BleDevice device = mDeviceAdapter.getData().get(position);
            LoadingDialogManager.get().showBigLoading(mActivity);
            mBLEManager.BLEReadConnect(device);
        });
    }


    @Override
    protected void dataObserver() {

        LiveEventBus.get().with(Constants.EVENT_BLE_WRITE, String.class).observe(this, s -> {
            if (mBLEManager != null) {
                isEdit = true;
                LoadingDialogManager.get().showBigLoading(mActivity);
                mBLEManager.BLEWriteData(mBleDevice, s);
            }
        });
    }

    @Override
    public void onNetworkConnectionChanged(boolean isConnected, NetWorkUtil.NetworkType networkType) {
    }


    @Override
    protected void initViews(View view) {
        mFlRootCircle = view.findViewById(R.id.fl_root_circle);
        mLoadingCircleView = view.findViewById(R.id.fl_loading_circle);
        mFlClickCircle = view.findViewById(R.id.fl_click_circle);
        mIvBleCenter = view.findViewById(R.id.iv_ble_center);
        mLlTopRightBox = view.findViewById(R.id.ll_top_right_box);
        mTvTotalDevice = view.findViewById(R.id.tv_total_device);
        mTvRescan = view.findViewById(R.id.tv_rescan);
        mFlListBox = view.findViewById(R.id.fl_list_box);
        mRvDevice = view.findViewById(R.id.rv_device);
        mTvScanTips = view.findViewById(R.id.tv_scan_tips);
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();

        switch (id) {
            case R.id.fl_click_circle:
                //验证权限
                toogleGifAnim();
                break;
            case R.id.tv_rescan:
                //重新扫描
                stopScanDevice();
                startScanDevice();
                startGifAnim();
                mTvScanTips.setText("正在检测，请稍等...");
                break;
        }
    }

    //切换GIF的动画和图片
    private void toogleGifAnim() {
        if (isCenterGifRuning) {
            //关闭动画
            stopGifAnim();
            mTvScanTips.setText("点击按钮，开始检测");

            //停止扫描
            stopScanDevice();
        } else {
            startGifAnim();
            mTvScanTips.setText("正在检测，请稍等...");

            //开启扫描
            startScanDevice();
        }

    }

    //开启蓝牙扫描和停止蓝牙扫描
    private void startScanDevice() {
        mDeviceAdapter.getData().clear();
        mDeviceAdapter.notifyDataSetChanged();

        mBLEManager.BLEStarScan();
    }

    private void stopScanDevice() {
        mBLEManager.BLEStopScan();
    }

    //开启GIF的动画
    private void startGifAnim() {
        //开启动画
        mIvBleCenter.setImageResource(R.drawable.anim_ble_loading);
        mAnimationDrawable = (AnimationDrawable) mIvBleCenter.getDrawable();
        mAnimationDrawable.start();

        mLoadingCircleView.setBackground(CommUtils.getDrawable(R.drawable.roate_scan1));
        //开启属性动画
        mAnimator = ObjectAnimator.ofFloat(mLoadingCircleView, "rotation", 0, 360);
        // 设置动画重复播放次数 = 重放次数+1
        // 动画播放次数 = infinite时,动画无限重复
        mAnimator.setRepeatCount(ValueAnimator.INFINITE);
        // 设置动画运行的时长
        mAnimator.setDuration(1250);
        // 设置动画延迟播放时间
        mAnimator.setStartDelay(0);
        // 设置重复播放动画模式
        mAnimator.setRepeatMode(ValueAnimator.RESTART);
        mAnimator.setInterpolator(new LinearInterpolator());
        mAnimator.start();

        isCenterGifRuning = true;

    }

    //关闭GIF的动画替换为图片
    private void stopGifAnim() {
        //关闭动画
        if (mAnimationDrawable != null) {
            mAnimationDrawable.stop();
        }
        if (mAnimator != null) {
            mLoadingCircleView.clearAnimation();
        }

        mIvBleCenter.setImageResource(R.drawable.blue_icon);

        mLoadingCircleView.setBackground(CommUtils.getDrawable(R.drawable.shape_circle_3));

        isCenterGifRuning = false;
    }

    //动画到顶部，并展示列表
    private void gotoTopShowList() {

        int top = mFlRootCircle.getTop();
        int left = mFlRootCircle.getLeft();
        int width = mFlRootCircle.getWidth();
//        float needMoveX = left + 125.5f;
        float needMoveY = top - 20;
        float needMoveX = left + width / 2.8f;

        //Circle移动到Y轴0的位置
        ViewPropertyAnimator.animate(mFlRootCircle)
                .translationY(-needMoveY)
                .translationX(-needMoveX)
                .setDuration(500)
                .start();

        //右侧布局动画进来
        ViewPropertyAnimator.animate(mLlTopRightBox)
                .translationX(0)
                .setDuration(500)
                .start();

        //列表的布局动画上来
        ViewPropertyAnimator.animate(mFlListBox)
                .translationY(0)
                .setDuration(500)
                .start();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mBLEManager != null) mBLEManager.destroyBLE();
    }
}
